const jwt = require('jsonwebtoken')

const APPSECRET = '724a133cd300ceb5f4446584461d9bd3';
const ADMIN_APPSECRET = 'Ad' + APPSECRET + 'miN'
const USER_APPSECRET = 'Us' + APPSECRET + 'eR'

const verifyToken = (req, res, next) => {
    const authHeader = req.headers['authorization']
    const token = authHeader && authHeader.split(' ')[1]

    console.log('token: ' + token)

    if(!token) {
        return res.status(401).json({ error: '未提供token' })
    }

    jwt.verify( token, USER_APPSECRET, (err, user) => {
        if(err) {
            return res.status(403).json({ error: 'token无效或过期!' })
        }
        req.openId = user.openid
        console.log("verify openId: ", req.openId)
        req.user = user // 添加用户信息到请求对象中
        next()
    })
}

const verifyAdminToken = (req, res, next) => {
    const authHeader = req.headers['authorization']
    const token = authHeader && authHeader.split(' ')[1]

    console.log('token: ' + token)

    if(!token) {
        return res.status(401).json({ error: '未提供token' })
    }

    jwt.verify( token, ADMIN_APPSECRET, (err, admin) => {
        if(err) {
            return res.status(403).json({ error: 'token无效或过期!' })
        }
        req.adminName = admin.username // 添加用户信息到请求对象中
        console.log("adminName:", req.adminName)
        next()
    })
}

module.exports = {
    verifyToken,
    verifyAdminToken
}